package com.dongdongshop.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.dongdongshop.constant.UserRegisterConstant;
import com.dongdongshop.pojo.TbUser;
import com.dongdongshop.result.Result;
import com.dongdongshop.result.ResultEnum;
import com.dongdongshop.service.UserService;
import com.dongdongshop.util.JavaMailUtils;
import org.apache.commons.lang3.RandomStringUtils;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.concurrent.TimeUnit;

@RequestMapping("user")
@Controller
public class UserController {

    private static final Logger logger = LoggerFactory.getLogger(UserController.class);

    @Autowired
    private RocketMQTemplate rocketMQTemplate;

    @Autowired
    private RedisTemplate redisTemplate;


    @Autowired
    private JavaMailUtils javaMailUtils;
    @Reference
    private UserService userService;

    @RequestMapping("toRegister")
    public String toRegister(){
        return "register";
    }

    @RequestMapping("getPhoneCode")
    @ResponseBody
    public Result getPhoneCode(String phoneNum){
        try {
            //生成6位数的手机验证码
            String code = RandomStringUtils.randomNumeric(6);
            //将手机号和验证码存到redis中
            redisTemplate.boundHashOps(UserRegisterConstant.USER_REGISTER_KEY).delete(phoneNum);
            redisTemplate.boundHashOps(UserRegisterConstant.USER_REGISTER_KEY).put(phoneNum,code);
            redisTemplate.boundHashOps(UserRegisterConstant.USER_REGISTER_KEY).expire(5, TimeUnit.MINUTES);
            //调用rockMq,阿里大于发送短信
            List<String> list = new ArrayList<>();
            list.add(phoneNum);
            list.add(code);
            rocketMQTemplate.convertAndSend("userRegisterPhoneCode",list);
            return Result.jsonResponse(ResultEnum.OK);
        }catch (Exception e){
            logger.error("系统错误"+e);
            return Result.jsonResponse(ResultEnum.INTERNAL_SERVER_ERROR);
        }
    }

    @RequestMapping("userRegister")
    @ResponseBody
    public Result userRegister(TbUser tbUser,String userCode){
        String code = (String) redisTemplate.boundHashOps(UserRegisterConstant.USER_REGISTER_KEY).get(tbUser.getPhone());
        if (!code.equals(userCode)){
            return new Result(10,"验证码错误");
        }
        try {
            int i = userService.insertUser(tbUser);
            return Result.jsonResponse(ResultEnum.OK);
        }catch (Exception e){
            logger.error("系统错误",e);
            return Result.jsonResponse(ResultEnum.INTERNAL_SERVER_ERROR);
        }

    }

    @RequestMapping("toIndex")
    public String toIndex(Model model){
        TbUser tbUser = (TbUser) SecurityUtils.getSubject().getPrincipal();
        model.addAttribute("tbUser",tbUser.getUsername());
        return "index";
    }

    @RequestMapping("toUserLogin")
    public String toUserLogin(){
        return "login";
    }

    @RequestMapping("userLogin")
    public String userLogin(String username, String password, Model model){
        if ("".equals(username) || null == username
                || "".equals(password) || null == password){
            model.addAttribute("message","密码或用户名不能为空");
            return "login";
        }
        Subject subject = SecurityUtils.getSubject();
        UsernamePasswordToken token = new UsernamePasswordToken(username,password);
        try {
            subject.login(token);
            return "redirect:/user/toIndex";
        }catch (UnknownAccountException e){
            model.addAttribute("message","用户名不存在");
            return "login";
        }catch (IncorrectCredentialsException e){
            model.addAttribute("message","密码错误");
            return "login";
        }
    }

    @RequestMapping("getBackPassword")
    public String ResetPassword(){

            return "reset";
    }

    @RequestMapping("backPassword")
    @ResponseBody
    public Result findMyPassword(String phone){
        Random random = new Random();
        int num = (int) (random.nextDouble() * (99999 - 10000 + 1)) + 10000;
        String pwd = num+"";
        try {
            TbUser tbUser = userService.getUserByPhone(phone);
            if (tbUser == null){
                return Result.jsonResponse(ResultEnum.FIND_PHONE_NULL);
            }
            tbUser.setPassword(pwd);
            int i = userService.findMyPassword(tbUser);
            javaMailUtils.sendSimpleMail("找回密码","你的密码为:"+num+"",tbUser.getEmail());
            return Result.jsonResponse(ResultEnum.OK);
        }catch (Exception e){
            logger.error("系统错误",e);
            return Result.jsonResponse(ResultEnum.INTERNAL_SERVER_ERROR);
        }

    }
}
